package com.dolphin.component.desktop;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述:
 * ${DESCRIPTION}
 *
 * @author 小海豚
 * @create 2022-09-17 22:39
 * 个人博客地址：https://www.nonelonely.com
 */
@ServerEndpoint("/webSocket/DeskTopWebServer")
@Component
public class DeskTopWebServer {


    public static Map<String, Session> deskTopWebServerSessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        String id = session.getId();
        if (deskTopWebServerSessionMap.containsKey(id)) {
            deskTopWebServerSessionMap.remove(id);
            deskTopWebServerSessionMap.put(id, session);
        } else {
            deskTopWebServerSessionMap.put(id, session);
            sendMessage("你好啊客户端" + id, session);
        }
    }

    @OnClose
    public void onClose(Session session) {
        for (String userId : deskTopWebServerSessionMap.keySet()) {
            if (deskTopWebServerSessionMap.get(userId).equals(session)) {
                deskTopWebServerSessionMap.remove(userId);
            }
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("服务端收到客户端的消息：" + message);
        this.sendMessage("Hello, " + message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    private void sendMessage(String message, Session toSession) {
        try {
            System.out.println("服务端给客户端发送消息：" + message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("服务端给客户端发送消息失败：" + e.getMessage());
        }
    }
}
